using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;

namespace Pixysoft.Data
{
    public class ObjectTableMapping
    {
        private static ObjectTableMapping instance;
        public static ObjectTableMapping Instance
        {
            get
            {
                lock (typeof(ObjectTableMapping))
                {
                    if (instance == null)
                        instance = new ObjectTableMapping();
                    return instance;
                }
            }
        }

        public DataTable GetDataTable(object target)
        {
            if (target == null)
                return null;

            Type objType = target.GetType();

            DataTable table = new DataTable();

            foreach (PropertyInfo info in objType.GetProperties())
            {
                if (info.PropertyType.IsValueType || info.PropertyType.Equals(typeof(string)))
                {
                    try
                    {
                        table.Columns.Add(info.Name, info.PropertyType);
                    }
                    catch { }
                }
            }

            DataRow row = table.NewRow();
            foreach (PropertyInfo info in objType.GetProperties())
            {
                if (info.PropertyType.IsValueType || info.PropertyType.Equals(typeof(string)))
                {
                    try { row[info.Name] = info.GetValue(target, null); }
                    catch { }
                }
            }
            table.Rows.Add(row);

            table.TableName = target.ToString();

            return table;
        }

        public void FillObject(object target, DataTable table)
        {
            if (target == null)
                return;

            if (table == null)
                return;

            if (table.Columns.Count == 0)
                return;

            if (table.Rows.Count == 0)
                return;

            Type objType = target.GetType();

            foreach (PropertyInfo info in objType.GetProperties())
            {
                if (table.Columns.Contains(info.Name))
                    try
                    {
                        info.SetValue(target, table.Rows[0][info.Name], null);
                    }
                    catch { }
            }
        }
    }
}
